package club.zhilin.guli.service.oss.controller.admin;

import club.zhilin.guli.common.base.result.CommonResult;
import club.zhilin.guli.common.base.result.CommonResultCodeEnum;
import club.zhilin.guli.service.base.exception.GlobalException;
import club.zhilin.guli.service.oss.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhilin
 * @since 2022/1/20 16:17
 */
@Api(tags = "阿里云文件管理")
@Slf4j
@RestController
@RequestMapping("/admin/oss/file")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class FileController {

    private final IFileService iFileService;

    @ApiOperation(value = "文件上传")
    @PostMapping("/upload")
    public CommonResult<Map<String, String>> upload(@ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file, @ApiParam(value = "模块", required = true) @RequestParam("module") String module) {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String upload = iFileService.upload(inputStream, module, originalFilename);
            Map<String, String> result = new HashMap<>(1);
            result.put("url", upload);
            return CommonResult.success("文件上传成功", result);
        } catch (IOException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GlobalException(CommonResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @ApiOperation(value = "文件删除")
    @DeleteMapping("/deleteFile")
    public CommonResult<String> deleteFile(@RequestBody String url) {
        iFileService.removeFile(url);
        return CommonResult.success("文件删除成功");
    }
}
